package cn.com.haopy.yue.ai.wx.utils;

import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class CheckApiUtil {
    /**
     * js转化为实体
     *
     * @param <T>
     * @param jsonstr
     * @param cls
     * @return
     */
	/*public static <T> T json2Obj(String jsonstr, Class<T> cls) {
		JSONObject jo = JSONObject.fromObject(jsonstr);
		T obj = (T) JSONObject.toBean(jo, cls);
		return obj;
	}*/
    public static <T> T json2Obj(String jsonstr, Class<T> cls) {
        //JSONObject jo = JSONObject.parseObject(jsonstr);
        T obj = (T) JSONObject.parseObject(jsonstr, cls);
        return obj;
    }

    /**
     * md5
     *
     * @param b
     * @return
     */
    public static String md5(byte[] b) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(b);
            byte[] hash = md.digest();
            StringBuffer outStrBuf = new StringBuffer(32);
            for (int i = 0; i < hash.length; i++) {
                int v = hash[i] & 0xFF;
                if (v < 16) {
                    outStrBuf.append('0');
                }
                outStrBuf.append(Integer.toString(v, 16).toLowerCase());
            }
            return outStrBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return new String(b);
        }
    }

    /**
     * 判断字符串是否为空
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        if (s == null || "".equals(s.trim()))
            return true;
        return false;
    }


    public static Map<String, Object> unionSign(Map<String, Object> params, String appId, String appSecret) throws Exception {
        // TODO Auto-generated method stub
        params.remove("sign");
        if (isEmpty(appSecret)) {// 如果是md5则需要把md5的key加入到排序
            throw new Exception("appSecret 为空");
        }
        params.put("appId", appId);
        StringBuilder sb = new StringBuilder();

        List<Map.Entry<String, Object>> fruitList = new ArrayList<>(params.entrySet());
        Collections.sort(fruitList, new Comparator<Map.Entry<String, Object>>() {
            @Override
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                // 按字母升序排列
                String val1 = o1.getKey().toString();
                String val2 = o2.getKey().toString();
                return val1.compareTo(val2);
            }
        });

        for (Map.Entry<String, Object> entry : fruitList) {
            if (entry.getValue() != null) {
                sb.append(entry.getKey()).append("=").append(entry.getValue())
                        .append("&");
            }
        }

        String endStr = "appSecret=" + appSecret;
        String sign = "";
        String signStr = sb.toString() + endStr;
        System.out.println(signStr);
        sign = md5(signStr.getBytes("UTF-8"));// 记得是md5编码的加签
        System.out.println("sign:" + sign);
        params.put("sign", sign);
        return params;

    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public static JSONObject handleResult(JSONObject result) throws Exception {

        if (result == null) {
            throw new Exception("返回数据错误");
        }
        if (result.getInteger("errno").equals(0)) {
            System.out.println("result:" + result);
            return result;
        } else {
            throw new Exception(result.get("errmsg").toString());
        }
    }

}
